package io.renren.common.utils;

import com.baomidou.mybatisplus.core.conditions.AbstractWrapper;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * JPA工具类
 * */
public class JPAUtil {
    private static Map<String, BaseMapper> mapperMap = new HashMap<>();

    public static void pushDao(String entityName, BaseMapper m) {
        mapperMap.put(entityName, m);
    }
    public static <T> T selectById(Class cls,Long id) {
        BaseMapper m = mapperMap.get(cls.getSimpleName());
        return (T) m.selectById(id);
    }
    public static  void save(Object o ) {
        Class cls = o.getClass();
        BaseMapper m = mapperMap.get(cls.getSimpleName());
        m.insert(o);
    }
    public static void update(Object o ) {
        Class cls = o.getClass();
        BaseMapper m = mapperMap.get(cls.getSimpleName());
        m.updateById(o);
    }
    public static <T> T selectById(Class cls,  Wrapper<Object> queryWrapper) {
        BaseMapper m = mapperMap.get(cls.getSimpleName());
        List list = m.selectList(queryWrapper);
        if(list.size()>0){
            return (T)list.get(0);
        }else {
            return null;
        }
    }
    public static QueryWrapper<Object> eq(String col, Object val){
        QueryWrapper<Object> queryWrapper =new QueryWrapper();
        return  queryWrapper.eq(col,val);
    }
    public static QueryWrapper<Object>  like(String col,Object val){
        QueryWrapper<Object> queryWrapper =new QueryWrapper();
        return  queryWrapper.like(col,val);
    }
}
